/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package elaborate.tool.messenger.secret;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

/**
 *
 * @author  lendle
 */
public class BlowFishEncrypter implements Encrypter{

    @Override
    public byte[] encrypt(byte[] key, String originalString) throws Exception {
        Cipher cipher=Cipher.getInstance("BlowFish");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "BlowFish"));
        return cipher.doFinal(originalString.getBytes("utf-8"));
    }

    @Override
    public String decrypt(byte[] key, byte[] secret) throws Exception {
        Cipher cipher=Cipher.getInstance("BlowFish");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "BlowFish"));
        byte [] originalBytes=cipher.doFinal(secret);
        return new String(originalBytes, "utf-8");
    }

    @Override
    public String encryptString(String key, String originalString) throws Exception {
        Base64 base64=new Base64();
        byte [] secret=this.encrypt(base64.decode(key), originalString);
        return base64.encodeToString(secret);
    }

    @Override
    public String decryptString(String key, String secret) throws Exception {
        Base64 base64=new Base64();
        return this.decrypt(base64.decode(key), base64.decode(secret));
    }
    
    public static void main(String [] args) throws Exception{
        BlowFishEncrypter encrypter=new BlowFishEncrypter();
        String original="這是一個test123";
        String secret=encrypter.encryptString("lendle", original);
        System.out.println("secret="+secret+"...");
        System.out.println("original="+encrypter.decryptString("lendle", secret));
    }
}
